package com.springboot.config;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * com.springboot.config
 * Created by ASUS on 2017/6/24.
 * 13:30
 */
public class CorsConfig implements Filter{
    public static String origin="http://localhost:8080";
    public static String header="Content-Type";
    public static String method="GET, POST, PUT, DELETE";


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        recordCors(httpServletRequest,httpServletResponse);
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }

    public static void recordCors(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse){
        httpServletResponse.setHeader("Access-Control-Allow-Origin",httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", method);
        httpServletResponse.setHeader("Access-Control-Allow-Headers", header);
        httpServletResponse.setHeader("Access-Control-Allow-Credentials","true");
    }

    public static void main(String[] args) {
        List<Long> a= Arrays.asList(2L,2L,2L,3L,4L,3L,5L);
        System.out.println(a);
        System.out.println(a.stream().distinct().collect(Collectors.toList()));
    }
}
